package cs236369.hw5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet({"/SearchResults", "/SearchResults/*"})
public class SearchResults extends HttpServlet {
	private static final long serialVersionUID = 7812126352690116420L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			out = response.getWriter();
			extractParameters(request);
			
			ArrayList<Post> tasks = DBConnection.searchPosts(latitude, longitude, radius, 0, null);
			ArrayList<Post> teams = DBConnection.searchPosts(latitude, longitude, radius, 1, null);
			out.print("<div id=\"teamResults\"><p class=\"topic\">Teams:<br/>\n Click on a team to open the team's page</p>\n <p class=\"text\">\n");
			for(Post post : teams) {
				out.println("<label onclick=\"loadToMainContent(\'team.jsp?postId=" +
						post.getId() + "\')\">id " + post.getId() + ": " + post.getName() + "</label><br />\n");
			}
			out.println("</p></div><br />\n<div id=\"taskResults\"><p class=\"topic\">Tasks:<br />\nClick on a task to open the task's page</p>\n<p class=\"text\">");
			for(Post post : tasks) {
				out.println("<label onclick=\"loadToMainContent(\'task.jsp?postId=" +
						post.getId() + "\')\">id " + post.getId() + ": " + post.getName() + "</label><br />\n");
			}
			out.println("</p><div>");
		} catch (IOException e) {
			response.setStatus(400);
			return;
		} catch (RescueMeException e) {
			response.setStatus(400);
			out.print(e.getMessage());
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private void extractParameters(HttpServletRequest request) throws RescueMeException {
		if(request.getParameter("radius") == null) {
			throw new RescueMeException("ilegal parameter", "Radius parameter is missing");
		}
		radius = Double.parseDouble(request.getParameter("radius"));
		if(radius <= 0) {
			throw new RescueMeException("ilegal parameter", "Radius must be a positive number");
		}	
		latitude = Double.parseDouble(request.getParameter("latPos")); 
		longitude = Double.parseDouble(request.getParameter("lngPos"));
		if(latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
			throw new RescueMeException("illegal parameter", "Incorrect position");
		}
	}

	private double latitude, longitude, radius;
	private PrintWriter out;
}
